package com.jingdun.sport.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jingdun.sport.bean.model.*;
import com.jingdun.sport.common.constants.RedisConstants;
import com.jingdun.sport.common.util.PageParam;
import com.jingdun.sport.common.util.RedisUtil;
import com.jingdun.sport.service.RoomService;
import com.jingdun.sport.service.RoomUserRelationService;
import com.jingdun.sport.service.SportConfigService;
import com.jingdun.sport.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/sport/room/")
@Api(tags = "活动室接口")
public class RoomController {

    Room rooms;

    @Autowired
    private RoomService roomService;

    @Autowired
    private RoomUserRelationService roomUserRelationService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SportConfigService sportConfigService;

    /**
     * 发起活动室接口
     */
    @PostMapping("/addRoom")
    @ApiOperation(value = "发起活动室接口", notes = "发起活动室接口")
    public ResponseEntity<ApiResult> addRoom(@RequestBody Room room) {
        ApiResult apiResult = new ApiResult();

        if (null == room.getBeginDate()) {
            apiResult.setMsg("请录入开始时间");
            return ResponseEntity.ok(apiResult);
        }

        if (null == room.getEndDate()) {
            apiResult.setMsg("请录入结束时间");
            return ResponseEntity.ok(apiResult);
        }

        //根据结束日期, 开始日期, 计算打开窗口数目
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            int windowsCount = (int) DateUtils.getDistanceOfTwoDate(sdf.parse(room.getBeginDate()), sdf.parse(room.getEndDate())) + 1;
            room.setWindowsCount(windowsCount);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        int prizeType = room.getPrizeType();
        if (prizeType == 1) {
            if (null == room.getDeposit()) {
                apiResult.setMsg("押金应该在0到20之间");
                return ResponseEntity.ok(apiResult);
            }
            double deposit = room.getDeposit();
            if (deposit <= 0 || deposit > 20) {
                apiResult.setMsg("押金应该在0到20之间");
                return ResponseEntity.ok(apiResult);
            }
        }

        //1押金, 2宝箱, 3冒险
        if (room.getPrizeType() == 1) {
            room.setEnabled("0");
        } else if (room.getPrizeType() == 2 || room.getPrizeType() == 3) {
            room.setEnabled("1");
        }

        Object count = redisTemplate.opsForValue().get(RedisConstants.CreateRoomMax + room.getSponsor());
        if (count == null) {
            redisTemplate.opsForValue().set(RedisConstants.CreateRoomMax + room.getSponsor(), "1");
        } else {
            if (Long.parseLong(count.toString()) > 20) {
                apiResult.setMsg("已超过每日创建房间最大数。");
                return ResponseEntity.ok(apiResult);
            }
        }

        //String userId = SecurityUtils.isUser() ? SecurityUtils.getUser().getUserId() : sendSmsParam.getMobile();
        //smsLogService.sendSms(SmsType.instance(sendSmsParam.getMsgType()), userId, sendSmsParam.getMobile(), Maps.newHashMap());

        //新建活动室
        roomService.addRoom(room);

        //获取房间id
        //mybatis设置useGeneratedKeys="true", 会自动回填id到room中
        //System.out.println("room.getSportProject() is " + room.getId());
        long roomIdIntGeneratedKey = room.getId();

        //发起者自动进入活动室
        //1押金, 2宝箱, 3冒险
        if (room.getPrizeType() == 2 || room.getPrizeType() == 3) {
            RoomUserRelation roomUserRelation = new RoomUserRelation();
            roomUserRelation.setRoomId(roomIdIntGeneratedKey);
            roomUserRelation.setUserId(room.getSponsor());
            roomUserRelationService.addRoomUserRelation(roomUserRelation);

        }
        redisTemplate.opsForSet().add(RedisConstants.StudyPageJoinPerson + room.getSportProject(), room.getSponsor());
        //return ResponseEntity.ok().build();
        apiResult.setData(room);
        return ResponseEntity.ok(apiResult);
    }

    /**
     * 获取活动室详情
     */
    @GetMapping("/getRoomDetail")
    @ApiOperation(value = "获取活动室详情", notes = "获取活动室详情")
    public ApiResult getRoomDetail(long id) {
        Map m = new HashMap<String, Object>();
        m.put("id", id);
        Room room = roomService.getRoomDetail(m);
        room.setPassword(StringUtils.isEmpty(room.getPassword()) ? "" : "1");
        //return room;
        ApiResult apiResult = new ApiResult();
        apiResult.setData(room);
        return apiResult;
    }

    /**
     * 获取活动室详情
     */
    @GetMapping("/getRoomInfo")
    @ApiOperation(value = "获取活动室详情", notes = "获取活动室详情")
    public ApiResult getRoomInfo(long id) {
        Room room = roomService.getById(id);
        //return room;
        ApiResult apiResult = new ApiResult();
        apiResult.setData(room);
        return apiResult;
    }

    /**
     * 分页获取某个奖品类型的活动室接口
     */
    @RequestMapping("/getPaginationRoomByPrizeType")
    @ApiOperation(value = "分页获取某个奖品类型的活动室接口，orderBy，1创建时间，2玩法，3房主名称，desc，desc降序，asc升序", notes = "分页获取某个奖品类型的活动室接口")
    public ResponseEntity<ApiResult> getPaginationRoomByPrizeType(
            String userId, long size, long current, @RequestParam(required = false) Long sportCategory, @RequestParam(value = "orderBy", defaultValue = "1") Integer orderBy, @RequestParam(value = "desc", defaultValue = "desc") String desc) {
        Map m = new HashMap<String, Object>();

        m.put("size", size);
        m.put("current", current);
//        m.put("prizeType", prizeType);
        m.put("sportCategory", sportCategory);
        m.put("userId", userId);
        String ob = null;
        switch (orderBy) {
            case 1:
                ob = "t1.create_date";
                break;
            case 2:
                ob = "t1.prize_type";
                break;
            case 3:
                ob = "t1.sponsor";
                break;
            case 4:
                ob = "t1.sport_project";
                break;
            default:
                ob = "t1.create_date";
        }
        m.put("orderBy", ob);
        m.put("desc", desc == null && !"desc".equals(desc) && !"asc".equals(desc) ? "desc" : desc);
        rooms = new Room();
        //获取活动室列表
        Page<GetPaginationRoomByPrizeTypeResp> paginationRoomByPrizeTypeRespPage = null;
        try {
            paginationRoomByPrizeTypeRespPage = roomService.getPaginationRoomBySportCategory(m);
        } catch (Exception e) {
            e.printStackTrace();
        }
        paginationRoomByPrizeTypeRespPage.getRecords().stream().forEach(getPaginationRoomByPrizeTypeResp -> {
            QueryWrapper<RoomUserRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("room_id", getPaginationRoomByPrizeTypeResp.getId());
            int count = roomUserRelationService.count(queryWrapper);
            getPaginationRoomByPrizeTypeResp.setJoinCounter(count);
        });
        ApiResult apiResult = new ApiResult();
        apiResult.setData(paginationRoomByPrizeTypeRespPage);
        return ResponseEntity.ok(apiResult);
    }


    /**
     * 分页获取某个奖品类型的活动室接口
     */
    @RequestMapping("/newListTypes")
    @ApiOperation(value = "活动列表类型", notes = "活动列表类型")
    public ResponseEntity<ApiResult> newListTypes(String userId, long size, long current, int prizeType) {
        //long roomId = 253;
        //String userId = "aumqtt2m16wa4tc5ahp22f1v48bwygoq";
        Map m = new HashMap<String, Object>();

        m.put("size", size);
        m.put("current", current);
        m.put("prizeType", prizeType);
        m.put("userId", userId);
        rooms = new Room();
//        //获取活动室列表
//        Page<Map<String, Object>> page = roomService.getPaginationRoomByPrizeType(m);
//        List<Map<String, Object>> datas = page.getRecords();
//        boolean bel = false;
//        int i = 0;
//        long roomId = 0;
//        for (Map<String, Object> map : datas) {
//            for (String s : map.keySet()) {
//                if (s.equals("id")) {
//                    i = 0;
//                    roomId = Long.valueOf((Long) map.get(s));
//                    // if(roomId == 236) {
//                    bel = true;
//                    m.put("roomId", roomId);
//                    // long roomId = Integer.valueOf((Integer) map.get(s));
//                    //获取其中一个活动室的人数
//                    Page<Map<String, Object>> page2 = roomUserRelationService.getPaginationRoomUserRelation(m);
//                    List<Map<String, Object>> datas2 = page2.getRecords();
//                    for (Map<String, Object> map2 : datas2) {
//                        for (String s2 : map2.keySet()) {
//                            String maps2 = (String) map2.get(s2);
//                            //rooms = new Room();
//                            System.out.print("获取的roomId是:" + roomId);
//                            System.out.print("获取的maps2是:" + maps2);
//                            //判断是否参加
//                            if (s2.equals("userId") && maps2.equals(userId)) {
//                                //System.out.print("获取的roomId是:" + roomId);
//                                rooms.setStatus("1");
//                                rooms.setId(roomId);
//                                roomService.updateRoom(rooms);
//                                //continue;
//                            }
//                            if (s2.equals("userId") && (roomId == Long.valueOf((Long) map.get(s)))) {
//                                // System.out.print("获取的map2是:" + map2.get(s2));
//                                i++;
//                                //continue;
//                            }
//                        }
//                    }
//                    // }
//                    // continue;
//                }
//            }
//            for (String s3 : map.keySet()) {
//                //判断是否满员
//                if (s3.equals("sport_participants_count")) {
//                    // System.out.print( "获取的roomId是:"+ roomId);
//                    System.out.print("获取的sport_participants_count是:" + (Integer.valueOf((Integer) map.get(s3))));
//                    if ((Integer.valueOf((Integer) map.get(s3)) == i) || Integer.valueOf((Integer) map.get(s3)) < i) {
//                        System.out.print("获取的i是:" + i);
//                        rooms.setId(roomId);
//                        rooms.setStatus("2");
//                        roomService.updateRoom(rooms);
//                        i = 0;
//                        //continue;
//                    }
//                }
//            }
//        }
        //获取活动室列
        Page<GetPaginationRoomByPrizeTypeResp> paginationRoomByPrizeTypeRespPage = roomService.getPaginationRoomByPrizeType(m);
        ApiResult apiResult = new ApiResult();
        apiResult.setData(paginationRoomByPrizeTypeRespPage);
        return ResponseEntity.ok(apiResult);
    }

//    /**
//     * 修改活动室接口
//     */
//    @PostMapping("/updateRoom")
//    @ApiOperation(value = "修改活动室接口", notes = "修改活动室接口")
//    public ResponseEntity updateRoom(@RequestBody Room room) {
//        roomService.updateRoom(room);
//        ApiResult apiResult = new ApiResult();
//        //return ResponseEntity.ok().build();
//        return ResponseEntity.ok(apiResult);
//    }

    /**
     * 修改活动室接口
     */
    @GetMapping("/listTypes")
    @ApiOperation(value = "学习页面", notes = "学习页面")
    public ResponseEntity listTypes(Integer parent, PageParam pageParam) {
        long current = pageParam.getCurrent();
        pageParam.setCurrent((pageParam.getCurrent() - 1) * pageParam.getSize());
        List<ListTypesResponse> listTypesResponses = roomService.getListTypes(parent, pageParam);
        for (ListTypesResponse listTypesResponse : listTypesResponses) {
            Long count = RedisUtil.get(RedisConstants.SportTypePersonCount + listTypesResponse.getId());
            listTypesResponse.setCount(count);
        }
        Page<ListTypesResponse> page = new Page<>(current, pageParam.getSize());
        page.setRecords(listTypesResponses);
        return ResponseEntity.ok(page);
    }
}